package com.codeoss.framework.workflow.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.workflow.context.WorkflowContext;
import com.codeoss.framework.workflow.def.WorkflowDef;
import com.codeoss.framework.workflow.store.IWorkflowStore;
import com.codeoss.module.workflow.model.WorkflowActivityInstance;
import com.codeoss.module.workflow.model.WorkflowProcess;
import com.codeoss.module.workflow.service.IWorkflowActivityInstanceService;
import com.codeoss.module.workflow.service.IWorkflowProcessService;

@Service
public class EndNodeService extends AbstractNodeService {
    @Autowired
    private IWorkflowActivityInstanceService workflowActivityInstanceService;
    @Autowired
    private IWorkflowProcessService workflowProcessService;
    @Autowired
    private IWorkflowStore workflowStore;
    @Autowired
    private IScriptServiceStore scriptServiceStore;
	@Override
	@Transactional
	public void end(WorkflowContext workflowContext) {
		WorkflowActivityInstance workflowActivityInstance=workflowContext.getWorkflowActivityInstance();
		workflowActivityInstance.setEndDate(new Timestamp(System.currentTimeMillis()));
		workflowActivityInstance.setState("CO");
		workflowActivityInstanceService.update(workflowActivityInstance);
		
		WorkflowProcess workflowProcess=workflowContext.getWorkflowProcess();
		workflowProcess.setState("CO");
		workflowProcess.setEndDate(new Timestamp(System.currentTimeMillis()));
		workflowProcessService.update(workflowProcess);
		executeEndExpression(workflowContext);
	    
		WorkflowDef workflowDef=workflowStore.get(workflowProcess.getWorkflowWorkflowId());
		Expression endEventExpression=workflowDef.getEndEventExpression();
		if(endEventExpression!=null) {
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("workflowContext", workflowContext);
			scriptServiceStore.getScriptService(endEventExpression).eval(endEventExpression.getScript(), paraMap);
		}
	}
}

